﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Globalization;
using System.Text;

namespace BizTalk.ESB.Extensions.PipelineComponents
{
    public class ContextPropertyTypeConverter : ExpandableObjectConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                string contextPropertyString = ((string)value).Trim();

                //Parse the format "PropertyName, PropertyNamespace"
                int comma = contextPropertyString.IndexOf(',');
                if (comma != -1)
                {
                    string[] contextPropertyStrings = contextPropertyString.Split(',');

                    if (contextPropertyStrings.Length == 2)
                    {                        
                         var contextProperty = new ContextProperty();
                         contextProperty.PropertyName = contextPropertyStrings[0];
                         contextProperty.PropertyNamespace = contextPropertyStrings[1];

                         return contextProperty;
                    }
                }
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if ((destinationType == typeof(string)) && value is ContextProperty)
            {
                var contextProperty = (ContextProperty)value;

                //Simply build the string

                if (string.IsNullOrEmpty(contextProperty.PropertyName) && string.IsNullOrEmpty(contextProperty.PropertyNamespace))
                    return string.Empty;

                return contextProperty.PropertyName + "," + contextProperty.PropertyNamespace;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
